const { 
  studentRegister,
  getPhoneNumber, 
  getUserProfile, 
  profileArchiveInformation,
  updateBasicInformation,
  deleteEducationalExperience
} = require('../../../../api/index');
const { getBatchDict, getDict } = require('../../../../utils/dict'); 

const {
  validate
} = require('../../../../utils/util');

// pages/authentication/index/index.js
Page({
  /*** 页面的初始数据 */
  data: {
    selectSchool: 'register2',
    title: '',
    genderDicts: [],
    educationDicts: [],
    formData: {
      student: {
        phone: "",
        realName: '',
        gender: "0",
        genderName: '',
        identityCard: '',
        highSchool: '',
        highestEducation: '',
        avatar: "",
        openId: wx.getStorageSync('openid'),
        workUnit: '', //  工作单位
        interest: '', // 兴趣爱好 
        strongPoint: '', // 特长
        otherRequirement: '',  // 其他需求
      },
      educationalExperienceList: []
    },
    //  需要进行上传的 表单
    baseFormData: {
      id: "",
      avatar: "",
      phone: "",
      highSchool: '',
      highestEducation: "",
      highestEducationName: "",
      workUnit: "",
      strongPoint: "",
      interest: "",
      otherRequirement: ""
    },
    errors: {},
    rules: {
      phone: [
        {
          empty: true,
          msg: '手机号码不能为空'
        },
        {
          rule: val => /^1(3|4|5|6|7|8|9)\d{9}$/.test(val),
          msg: '手机号码格式有误'
        }
      ],
    },
    rules2: {
      educationalExperienceList: [
        {  
          empty: true,
          msg: '至少有一个教育经历'
        }
      ]
    }
  },
  //  获取用户基本信息
  async onGetUserProfile(event) {
    wx.showLoading({ title: '加载中...' });
    //  获取用户基本信息
    const res = await getUserProfile.call(this, event);
    const { gender, avatarUrl } = res.userInfo;
    //  获取字典项
    const dict = this.data.genderDicts.find(_d => _d.code == gender);
    this.data.formData.student.gender = dict.code;
    this.data.formData.student.genderName = dict.name;
    this.data.formData.student.avatar = avatarUrl;
    this.setData({ formData: JSON.parse(JSON.stringify(  this.data.formData )) });
    wx.hideLoading({ title: '加载中...' })
  },
  //  页面跳转
  onJump( event ) {
    const { url } = event.currentTarget.dataset;
    wx.navigateTo({ url });
  },
  onDelete( event ) {  //  删除 - 删除元素
    const { id } = event.currentTarget.dataset;
    fetchDeleteEducationalExperience.call(this, id);
  },
  onEdit( event ) {  //  编辑
    const { id, index } = event.currentTarget.dataset;

    wx.navigateTo({
      url: `/packageA/pages/authentication/addExperience2/index?id=${ id }&index=${ index }`
    })
  },
  //  修改表单数据
  onBaseFormData(event) {
    const { prop } = event.currentTarget.dataset;
    this.data.baseFormData[prop] = event.detail;
  },
  // 提交数据
  async onSubmit(event) {
    //  判断返回的错误集合是否是空的，如果空则说明验证通过了，否则将错误显示到页面上
    // const error = validate({ educationalExperienceList: this.data.formData.educationalExperienceList }, this.data.rules2) || {};
    const error2 = validate(this.data.baseFormData, this.data.rules) || {};
    const errorObj = Object.assign({}, error2);
    if ( JSON.stringify(errorObj) !== '{}' ) { //  如果报错就不允许进行数据的提交
      return this.setData({ errors: error });
    }

    //  更新基本信息
    fetchUpdateBasicInformation.call(this, this.data.baseFormData);
  },
  /*** 生命周期函数--监听页面加载 */
  async onLoad(options) {
    wx.showLoading({ title: '加载中...' });
    const { type, title } = options;
    await fetchDicts.call(this);
    await fetchProfileArchiveInformation.call(this);
    this.setData({ title });
    wx.hideLoading();
  },
  /*** 生命周期函数--监听页面显示 */
  onShow() {
    this.data.errors.educationalExperienceList = '';
    const educationalExperienceList = wx.getStorageSync('educationalExperienceList') || [];
    const collegeName = wx.getStorageSync(this.data.selectSchool)?.collegeName;
    this.data.formData.educationalExperienceList = educationalExperienceList;
    collegeName && ( this.data.baseFormData.highSchool = collegeName );

    this.setData({ 
      errors: JSON.parse(JSON.stringify(this.data.errors)),
      formData: JSON.parse(JSON.stringify( this.data.formData )),
      baseFormData: JSON.parse(JSON.stringify(this.data.baseFormData))
    }); 
  },
  /*** 生命周期函数--监听页面卸载 */
  onUnload() {
    //  卸载的时候清除掉缓存的数据
    wx.removeStorageSync('studentMsg');
    wx.removeStorageSync('educationalExperienceList');
    wx.removeStorageSync(this.data.selectSchool);
  },
})

//  删除教育经历
async function fetchDeleteEducationalExperience(id) {
  const { errors } = await deleteEducationalExperience({ id });
  if(errors.length > 0) { return; }

    //  填写完成之后 返回到上一页
    const url = '/pages/home/index';
    wx.navigateTo({ url: `/packageA/pages/success/index?type=delete_education&url=${ url }` });
}


//  更新基本信息
async function fetchUpdateBasicInformation(data) {
  const { errors = [] } = await updateBasicInformation(data);
  if(errors.length > 0) { return; }

   //  提交成功 跳转到 成功页面
   const url = '/pages/home/index';
   wx.navigateTo({ url: `/packageA/pages/success/index?type=base_message&url=${ url }` });
}

//  处理基本信息提交数据
async function setResult() {
  const _formData = JSON.parse(JSON.stringify(this.data.formData));
  return _formData;
}

//  获取档案信息
async function fetchProfileArchiveInformation() {
  const res = await profileArchiveInformation();
  if(res.errors.length > 0) { return; }
  if(res) {
    // 
  }
 
  //  处理回显数据
  getResult.call(this, res);
}

//  处理表单回显数据
async function getResult(data) {
  const _data = JSON.parse(JSON.stringify(data));
  _data.student.genderName = this.data.genderDicts.find(_s => _s.code == _data.student.gender)?.name;
  _data.educationalExperienceList = _data.educationalExperienceList.filter(_s => _s.auditFlag === '2'); 
  _data.student.highestEducationName = this.data.educationDicts.find(_s => _s.code == _data.student.highestEducation)?.name;

  //  缓存学子的基本信息
  this.setData({ 
    formData: JSON.parse(JSON.stringify( _data )),
    baseFormData: JSON.parse(JSON.stringify( _data.student ))
  });
 
  //  将教学经历进行缓存
  wx.setStorageSync('educationalExperienceList', _data.educationalExperienceList);
  return _data;
}

//  批量获取字典项
async function fetchDicts() {
  const [ genderDicts, educationDicts ] = await getBatchDict([ 'GENDER', 'EDUCATION' ]);
  this.data.genderDicts = genderDicts;
  console.log(educationDicts);
  this.data.educationDicts = educationDicts;
}